import React, { JSX } from 'react';
import { NulDialog, NulCommonOperations, NulFormItem } from '../../components/NulDialog';
import { TextField, Typography } from '@mui/material';
import { useAppDispatch } from '../../actions/hook';
import { SupplierEntry, modifySupplier } from '../../actions/SupplierManagement';
import '@fontsource/open-sans';

interface ModifySupplierProps {
  open: boolean;
  onClose: () => void;
  supplierEntry: SupplierEntry;
}

function ModifySupplier(props: ModifySupplierProps): JSX.Element {
  const { open, onClose, supplierEntry } = props;

  //console.log(supplierEntry);
  //console.log(supplierEntry.name);

  const [name, setName] = React.useState<string>(supplierEntry.name);
  const [contact, setContact] = React.useState<string>(supplierEntry.contact);
  const [phone, setPhone] = React.useState<string>(supplierEntry.phone);
  const [email, setEmail] = React.useState<string>(supplierEntry.email);
  const [address, setAddress] = React.useState<string>(supplierEntry.address);

  React.useEffect(() => {
    setName(supplierEntry.name);
    setContact(supplierEntry.contact);
    setPhone(supplierEntry.phone);
    setEmail(supplierEntry.email);
    setAddress(supplierEntry.address);
  }, [supplierEntry]);

  const dispatch = useAppDispatch();

  const onModifyClicked = () => {
    dispatch(modifySupplier({
      id: supplierEntry.id,
      name, contact, phone, email, address
    }));
    onClose();
  };

  return (
    <NulDialog
      open={open}
      onClose={onClose}
      title='Edit Supplier'
      operations={
        <NulCommonOperations
          onPositiveClicked={onModifyClicked}
          onNegativeClicked={onClose}
          positiveText='Modify'
        />
      }
    >
      <NulFormItem hint='ID' necessary={false} component={
        <Typography>{supplierEntry.id}</Typography>
      } />
      <NulFormItem hint='Name' component={
        <TextField placeholder='Name' fullWidth={true} size='small' value={name} onChange={(event) => { setName(event.target.value); }} />
      } />
      <NulFormItem hint='Contact' component={
        <TextField placeholder='Contact Person Name' fullWidth={true} size='small' value={contact} onChange={(event) => { setContact(event.target.value); }} />
      } />
      <NulFormItem hint='Phone' component={
        <TextField placeholder='Phone Number' fullWidth={true} size='small' value={phone} onChange={(event) => { setPhone(event.target.value); }} />
      } />
      <NulFormItem hint='E-mail' component={
        <TextField placeholder='E-mail' fullWidth={true} size='small' value={email} onChange={(event) => { setEmail(event.target.value); }} />
      } />
      <NulFormItem hint='Address' component={
        <TextField placeholder='Address' fullWidth={true} size='small' value={address} onChange={(event) => { setAddress(event.target.value); }} />
      } />
    </NulDialog>
  );
}

export { ModifySupplier };